Java versus JavaScript
by Andrew Wooldridge
- How Java and JavaScript differ
Java and JavaScript are quite different in origin, scope, and
complexity.
- How to include JavaScript in your HTML
JavaScript is similar to Java in that you use special tags to
delineate it from the rest of your HTML
- The benefits of JavaScript over Java
JavaScript is easy to learn and allows greater interactivity
in Web pages without server-side scripts.
If you have read this far, you should--by now--have a pretty
good idea of what Java is and what it can do for you. Now that
you are approaching the end of this book, it is time to introduce
you to another language you will encounter if you plan to build
java applets on the Web. The next few chapters bring you to a
greater understanding of the features of Netscape's new scripting
language, JavaScript. You learn how it differs from Sun's Java,
and how you can use JavaScript to dramatically enhance your Web
pages. You see that JavaScript and Java are distinct languages
that can work together in a Web browser environment to create
pages that are highly interactive.
Programmers often are confused by the similar names of Java and
JavaScript. If you were to say to a friend, "I program in
JavaScript," more often than not, that person will respond
with something like, "Oh, perhaps then you can help me with
this Java applet... ."
It is a common misconception that Java and JavaScript are just
part of the same language. This is far from true. Although they
are similarly named, there are quite a few differences between
them, the first of which is their origin. Around June of 1991,
Java was developed at Sun Microsystems, and was originally called
Oak. It was officially announced (after much development and a
name change) in May 1995 at SunWorld '95. JavaScript was developed
at Netscape Communications Corporation and was originally called
LiveScript. Sun renamed Oak to Java because of copyright issues
with another language already called Oak, and Netscape changed
LiveScript to JavaScript after an agreement with Sun to develop
JavaScript as a language for "non-programmers." JavaScript
was first released with Netscape 2.0.
Before you delve into some of the differences between these two
languages, let's get an overview of the major distinctive points
and then discuss each in more depth. Table 52.1 lists some of
the major distinctions between Java and JavaScript.
Table 52.1 JavaScript and Java
Comparison
|
JavaScript
|
Java
|
|
Developed by Netscape.
|
Developed by Sun.
|
|
Code is interpreted by client(Web browser).
|
Code is compiled and placed on server before execution
on client.
|
|
Object-based. Objects are built in and extensible but are
not classes and cannot use inheritance.
|
Object-oriented. Everything is a class that can use inheritance.
|
|
Data types need not be declared (loose typing).
|
Data types must be declared (strong typing).
|
|
Runtime check of object references (dynamic binding).
|
Compile-time check of object references (static binding).
|
|
Restricted disk access (must ask before writing a file).
|
Restricted disk access (levels of access set by user; cannot
automatically write to disk).
|
|
Scripts are limited to Web browser functionality.
|
Compiled code can run either as a Web applet or a stand-alone
application.
|
|
Scripts work with HTML elements (tags).
|
Can handle many kinds of elements (such as audio and video).
|
|
The language is rapidly evolving and changing in functionality.
|
Most major changes are complete.
|
|
There are few libraries of standard code libraries bundled
with the language.
|
Java comes with many code examples and with with which
to build Web applications.
|
JavaScript Is Not Java top
of page
The first thing you need to know is that JavaScript is not
Java. It is almost becoming a mantra for JavaScript programmers
who constantly face Java questions, even though the forum (such
as the newsgroup) is clearly JavaScript.
You can write JavaScript scripts and never use a single Java
applet. The reason JavaScript has adopted their name (in addition
to the agreement with Sun Microsystems) is because the language
has a similar syntax to Java. Netscape also recognized the momentum
building behind Java and leveraged the name to strengthen JavaScript.
If you have programmed in Java, then you will find that JavaScript
is both intuitive and easy for you to pick up. There will not
be very much new for you to learn. The nice thing about JavaScript,
though, is that you don't need to have any experience using Java
to rapidly create useful scripts.
To give you an example of the similar nomenclature in Java and
JavaScript, look at how each language would handle a specific
function called from a specific object.
Suppose in Java you have a class called MyClass that
contains a method called MyMethod. You could call MyMethod
in this way:
foo = new MyClass();
result = foo.MyMethod(parameter1, parameter2);
In JavaScript, you can do the same thing. If you have a function
called MyObject defined by:
function MyObject(parameter) {
this.firstone = parameter;
this.MyFunction = MyFunction;
}
(assuming now that MyFunction() has been previously
defined), you can then call MyFunction by:
foo = new MyObject(parameter);
foo.MyFunction(someparameter);
In the first part, you have created two properties (basically
slots for information inside the object) called firstone
and MyFunction. In the second part, you see how you can
create a specific instance of an object and use that new object's
methods.
There are many similarities like this between the languages.
See the next chapter for details of the JavaScript syntax.
Interpreted versus Compiled top
of page
JavaScript code is almost always placed within the HTML document
which it will be running. When you load a page that contains JavaScript
code, the Web browser contains a built-in interpreter that takes
the code as it is loaded and executes the instructions (sometimes
on-the-fly, before you see anything on that window). This means
that you can usually use "View Source" (choose View,
Document Source in the Netscape menu) to see the code inside the
HTML document.
JavaScript uses the <script>...</script>
tag, similar to Java's <applet>...</applet>
tag. Everything within the <script>...</script>
is ignored by Netscape's HTML parser, but is passed on to the
JavaScript interpreter. For Web browsers that do not support the
<script>...</script> tag, it is customary
to further enclose the JavaScript code in comments. Here is an
example in Listing 52.1.
Listing 52.1JavaScript Code
in an HTML Document
<html>
<head>
<title>JavaScript Hello!</title>
<script language="JavaScript">
<!-- // to hide from old browsers
var textData = "Hello World!";
function showWorld(textInput) {
document.write(textInput);
}
//to ignore end comment -->
</script>
</head>
<body bgcolor=white>
<script language="JavaScript">
<!--
showWorld(textData);
// -->
</script>
</body>
</html>
The script in Listing 52.1 shows how JavaScript can appear in
both the <head> and <body> elements
of an HTML document. This script would first load the function
within the <head> element (all of the code is read
from the top down--remember this when you refer to other pieces
of code so you don't refer to code that hasn't been loaded yet).
When the browser encounters the showWorld(textData) line
in the <body> element, the browser would display
the text value of textData--in this case, "Hello
World!".
If you were to do something similar in Java, you would write
the code in Java in an editor, compile the code to a .class file,
and place that file on your server. You would then use the now
familiar <applet>...</applet> to embed this
applet in your HTML document. For example, the Java code would
appear as:
public class HelloWorld extends java.applet.Applet {
public static void main (String args []) {
System.out.println("Hello World");
}
}
The HTML code would appear as:
<html>
<head>
<title>Java Example</title>
</head>
<body>
<applet code="HelloWorld.class" width=150 height=25>
</applet>
</body>
</html>
The benefits of having code interpreted by the browser instead
of compiled by a compiler and run through the browser is primarily
that you--as a JavaScript developer--can very quickly make modifications
to your code and test the results via the browser. If you use
Java, you must change the code, compile it, upload it again (if
you are testing on your own Web server), and then view it in your
browser. Interpreted code is typically not as fast as compiled
code, but for the limited scope of JavaScript, you will probably
see scripts run a little faster than their Java counterparts (with
equivalent functions, such as a scrolling text ticker).
The drawback to having your JavaScript code on the HTML document
is that any code you write will be exposed to anyone else who
accesses your page--even those who want to use your code for their
own projects. For small scripts, this is not much of a problem,
nor is it a problem for large projects, if you don't mind having
your efforts used on other pages or improved upon by others. If
you have a large project in which you want to keep your code private,
you might consider using Java instead. With the recent implementation
of the SRC attribute, your scripts can now be pulled out of the
HTML page and placed in their own file. This dramatically increases
their usefulness if you have scripts that you want to reuse often.
Overall, it is more convenient for JavaScript coders to be able
to see the results of their changes on-the-fly in the browser
than it is for the code/compile/upload/view of Java.
One feature of this interpreted nature of JavaScript is that
you can test out statements on-the-fly (such as eval(7*45/6)
or document.write("hi1")). If you are using
Netscape Navigator 2.0 or greater, try typing javascript:
or mocha: in the URL window. You see that the browser window
changes into interpreter mode with a large frame above a smaller
frame. You can type in JavaScript commands in the smaller frame
input box and see the results displayed in the larger frame.
Object-Based versus Object-Oriented top
of page
JavaScript takes liberally from Java in respect to its overall
language structure, but lacks many of the features that make Java
an object-oriented language. JavaScript has built-in objects (such
as Navigator, Window, or Date) that
access many browser elements such as windows, links, and images.
Java typically cannot access any of these browser elements and
is restricted to the area (or bounding box) that contains
it and any Java windows it subsequently creates.
JavaScript allows you to create new "objects" that
are really functions. Objects in JavaScript are not true objects
because they do not implement inheritance and other features that
Java does. For instance, you cannot create a new class MyWindow
that inherits properties of the JavaScript object window
(the top-level object in JavaScript).
Although this limitation may at first seem very constricting,
you can still create many useful functions within JavaScript that
can perform many of the same tasks that an equivalent Java applet
might do.
Due to these built-in objects, JavaScript really shines when
it comes to accessing or manipulating browser-based attributes,
such as the current time, the value of a given form element, the
third window in your browser, the link you visited five clicks
ago, and so on.
Java code can be written to allow a programmer to do just about
anything conceivable on a computer as a stand-alone application
or a Java applet. But, JavaScript fills a major gap (at least
in the context of Java applets and Web browsers) by acting as
a "glue" by which Java and the browser can communicate.
Via JavaScript, you could enter information into a form field
in an HTML document, and a Java applet on that page could use
that input to display new information. JavaScript allows Java
applets to gain access to properties of an HTML page, and allows
non-programmers access to various parts of a Java applet--such
as public variables.
Although JavaScript does not allow inheritance, there is an interesting
new feature called prototype. Prototype allows you to add
new properties to any object that you created (with the new
statement), and even add new properties to existing built-in objects.
What this means is you can extend existing instances of objects
even after they have been defined.
For example, you have an object House that has the properties
of Light, GarageDoor, and BurglarAlarm.
You might already have an instance of this called myHouse.
But now you want to extend House by adding ChimneySmoke.
Instead of re-defining all of your objects, you can use
House.prototype.ChimneySmoke = ChimneySmoke.
Now the instance called myHouse can access this new
property ChimneySmoke by using
myHouse.ChimneySmoke.
Strong Typing versus Loose Typing top
of page
When you are writing JavaScript code, variables don't need to
have data types when they are declared. This loose typing
means that it is much easier for JavaScript writers to work on
creating and manipulating variables without worrying if the data
was an int, float, and so on.
In Java, you must explicitly declare what data type a variable
will be before you use it. This is called strong typing
and contributes to the overall stability of Java code, but can
cause problems for new programmers. JavaScript allows you to ignore
this and assumes that the type of value you first assign to a
variable is the type you intended it to be. For instance, if you
had a variable HouseType and you assigned it a value
of "Victorian," JavaScript assumes you meant HouseType
to be a string all along and does not complain if you did not
specifically set HouseType to a string. However if you
had first assigned a value of 4 to HouseType, JavaScript
now assumes it is of type INT. Overall, this makes for
faster and easier script writing and eliminates needless debugging
for variable declarations. However, you must be careful to assign
the correct type of value to a variable.
This loose typing demonstrates one of the areas in which JavaScript
seeks to simplify the process of writing code. Because JavaScript
is directed toward "non-programmers" or "minimal"
programmers, the developers sought to simplify the language in
as many ways as possible while still keeping much of the flexibility.
Other examples of loose-typed language include HyperTalk, dBASE,
and AppleScript.
Dynamic versus Static Binding top
of page
Because JavaScript is interpreted on the client's browser, object
references are checked on-the-fly as opposed to Java's static
binding at compile time. Binding simply means that a variable
name is bound to a type--either statically through an explicit
declaration of a type with a variable, or dynamically through
an implicit association determined by the computer at compile
or runtime. Because of JavaScript's dynamic nature, objects in
JavaScript can be created on-the-fly as well, and might change
the functionality of the script due to some outside factor (time,
customer responses, and so on). The Date object is often
used to get information about the Web browser's current date,
time, day of the year, and more. This object is created at the
time the JavaScript code is interpreted in order to get the correct
information.
Java programs--with static binding--are typically more stable,
because the entire process of compiling the code has already been
completed via the Java compiler. Any bad or missing object references
have been corrected. This is an advantage when you want the given
application to load and run quickly on the user's machine.
Restricted Disk Access top
of page
Security is a hot issue in today's Internet and intranet Web
industry for many good reasons. One of the greatest fears people
have when they use the Web (or other Internet applications such
as e-mail) is that a hostile program will enter their computer
and damage or compromise their sensitive data. Java has a comprehensive
way of dealing with security that allows it to do useful things
on your computer while keeping it isolated from your sensitive
documents. Java applets typically cannot write to your hard drive
at all, or if they do, it is in some extremely limited way.
Because JavaScript can control so many aspects of your browser,
for a while there was some concern that JavaScript was less safe
than Java. This was primarily due to bugs in early versions of
JavaScript that allowed it to send the contents of the file containing
your bookmarks and e-mail address to another remote site through
a hidden form, or acquire a list of all the files on your machine.
These problems have since been eliminated, and JavaScript is now--for
the most part--as safe as any Java applet you might run via your
browser.
Note that JavaScript can write to your hard drive--an
essential feature that your Web browser has in order to write
to its cache or save files downloaded via the Web. However, it
requires now that you specifically click Accept in a dialog box
to download a file. In a sense, JavaScript is morfversatile than
Java in this respect, because it allows you to use your browser
to create files to save and work with at a later time.
If you are concerned that some kind of hostile code might damage
your machine, you should be aware that the possibility of virus
infection has been around for a long time. Java, with its assertion
of security, has only focused more attention to security issues.
Soon, with JavaScript's tainting (a system of marking data
so that it cannot be sent via a form or mailto: link via JavaScript)
and Java's digital signatures (an electronic verification
of the origin or identity of the code or information), you will
be able to verify that any code--be it Java or JavaScript--comes
from some trusted source. This is very good, because you will
be able to allow Java to perform more sensitive tasks such as
update your Oracle database, or send and auto-install updated
versions of software on your machine.
Also note that your Web browser (and JavaScript through the browser)
can also write information to a file called a cookie. This
is a file on your machine that allows Web sites to store information
about you that could be retrieved when you visit that site again.
Only the site that wrote the information to the cookie can retrieve
it, and it is usually only used to maintain some kind of temporary
information about you to carry across different pages (such as
a user ID, or the fact that you are from Florida).
Different Functionality (Scope Limitations) and Code Integration
with HTML top
of page
JavaScript is limited in scope to your Web browser (either Netscape
Navigator or Microsoft Internet Explorer). Java, on the other
hand, can run as a stand-alone application (like Microsoft Word)
or within the context of a browser as an applet. It is a testimony
of the versatility of Java that it has adapted so quickly to the
Web. It was originally intended to run as operating system and
controls on set-top boxes or other small communication appliances.
Given that Java will eventually outstrip C++ as the programming
language of choice (at least for Internet programmers, if not
for all programmers, as its speed increases), it has the functionality
and versatility to run in many different operating systems.
JavaScript is a smaller language for a more limited audience
of Web browser programmers. JavaScript gives to Web programmers
the capability to access and modify all of the HTML tags, form
elements, window elements, images, bookmarks, links, and anchors
in a Web browser. It enables the programmer to create Web sites
that respond and change based on many factors such as the time
of day, or some user profile. JavaScript allows Java applets,
scripts, and browser plug-ins to communicate with each other.
This actually is a suite of technologies called LiveConnect from
Netscape and requires some additional code in the Java applet
or plug-in to be "aware" of JavaScript.
JavaScript can create HTML files on-the-fly, change attributes
of a page instantly(such as the background color), and allows
the client machine to perform many functions that were traditionally
allowed only through cgi's, such as a TicTacToe game. JavaScript
allows for form input validation, where incorrect responses are
checked before they are sent back to the browser, which is much
more difficult to do in Java than in JavaScript. Essentially,
to get the functionality of JavaScript in Java, you would have
to rebuild a mini-browser into your code-- a fairly inefficient
solution.
Also, JavaScript can be integrated directly into the HTML of
your document. Event handlers, such as onClick, can modify
the behavior of your browser beyond just accessing new documents.
You can create simple calculators in JavaScript that take advantage
of the GUI already present in the browser, as well as the layout
capabilities already in place via the presence of HTML forms or
TABLE elements. In other words, you can use your browser
to do more than just access documents. You can use it as a front
end to just about any kind of application. If you use Java, you
have GUI capabilities, but you have to manually activate and resolve
these capabilities, which might require significant programming
on your part. In JavaScript, though, you let the browser handle
most of the GUI problems and concentrate on your creative project.
Here are some examples of how you can integrate JavaScript statements
into your HTML. You saw in Listing 52.1 how you can create scripts
via the <script> tag. You can also embed javascript
statement directly into your HTML:
<a href="" onMouseover="alert(`you noticed me!');">pass
your mouse over here for a message!</a>
Instead of showing the URL in the status bar, passing the mouse
over the text of the hyperlink will bring up a new dialog box
that displays the you noticed me! text. To do this in
Java, you would have to create an applet that draws the link text
to the screen, write the code that monitors the mouse location
(probably as a separate thread), and write more code to create
and destroy the resulting dialog box. Needless to say, the JavaScript
solution is much easier to implement for the casual Web designer.
Also, with LiveConnect, you can let a Java applet tell JavaScript
to open the window and do other tasks without having to write
additional code.
<img width="&{imgwidth}";%" height=40>
In this example, JavaScript allows you to set a value to an HTML
attribute via a JavaScript expression. In this case, if you had
defined imgwidth to be 50, the resulting image would
have a scaled width of 50 percent of the window size. Again, if
you had to do this in Java, you would have a significant amount
of code to create--just to mimic the same ability. Even then you
could not easily share the value of imgwidth with
other applets.
Overall, the ability to integrate JavaScript code directly in
the HTML source allows Web programmers to quickly take advantage
of the browser's built-in GUI. Casual scripters can both leverage
their HTML experience as well as any familiarity with Java. Java
allows you to create amazing new applications that can be executed
on many operating systems that have had the Java interpreter ported
to them.
The capacity for Java to create as diverse a range of applications
as C++ is not disputed. However, if you are a Web page designer
who doesn't have the time to learn how to program Java, you will
find that JavaScript is very useful. On the other hand, if you
dislike using proprietary code in your HTML that only functions
with two browsers (even though together they hold almost 90 percent
of the current browser market share), you may decide to tough
it out by using just Java.
Rapid Evolution versus Relative Stability top
of page
JavaScript is the newer of the two languages, and as such is
undergoing a more dramatic series of changes and improvements.
As of this writing, Java Version 1.0.2 is relatively stable. Most
of the statements, operators, syntax, and so on have been well-defined
and most likely will not change significantly in subsequent versions.
JavaScript has been rapidly evolving from the original goal of
providing form verification on the client-side (instead of a server-side
cgi) to having the potential to simulate a simple game such as
Pong or breakout. Some of the features of JavaScript include:
- Java-JavaScript communication
- JavaScript-Plugin communication
- Determination of installed plug-ins
- Data Tainting (security enhancements)
- Image "reflection" (dynamic listing of all images)
- New event handlers (onMouseOut and more)
- New attributes to the <script> tag (SRC)
- New built-in objects (array, string, and so on)
- New operators (typeof)
- Object prototypes
As you can see, JavaScript is changing and growing. It provides
a powerful way for non- programmers (or light programmers) to
do the following:
- Access Java applet methods.
- Enable plug-ins and applets to communicate with other elements
(other plug-ins, scripts and applets).
- Validate form information on the client-side (before it is
sent back to the Web server)
- Generate HTML on-the-fly or based on environment variables
(time, date, location, and so on)
- Create simple interactive programs (such as a TicTacToe game)
completely in JavaScript.
The drawback to this is subtle. It may seem at first that adding
new features with every new release of Netscape would be looked
upon as a wonderful thing. For the most part this is true, except
now when you sit down at your latest browser and begin programming
with JavaScript. You have to ask yourself if the feature you are
using is going to be available to a large audience (specifically,
the target audience for your Web site). Not everyone updates their
browser every few months, so every release tends to segment your
audience. Another drawback is that, for every feature added to
a language, it opens the possibility that a bug snuck in as well.
For now, it is a good strategy to take advantage of only those
features of JavaScript that have persisted through Version 2.02
of Netscape. If you use 3.0-specific features, be sure to mention
this on the page to inform your visitors. So, another difference
between Java and JavaScript is that, although Java is more powerful
and relatively stable as a language, JavaScript is growing with
each version.
It is exciting to see how much a scripter can do now with JavaScript.
With 3.0, I have seen simple paint programs, pong games, and even
LED clocks that change every second. Many of these scripts would
be fairly indistinguishable from their Java counterparts.
NOTE: If you discover a feature you would like to add
to JavaScript, you have the unique opportunity to talk to the
developer of JavaScript (Brendan Eich at Netscape). I expect
that the expansion of features in JavaScript will continue,
especially now that it is being compared to Microsoft's Visual
Basic Script. If you find JavaScript too limited in some way,
you may be able to change it in future versions. Brendan tries
to respond to all e-mail he gets, but with such a high volume,
it may take a while for him to respond--if at all.
Sun delivers Java with a standard set of libraries that act to
dramatically enhance its usefulness. Instead of having to write
all the code to handle images, sockets, and so on, the programmers
at Sun have done this for you. You simply have to learn the standard
APIs so you can quickly write terminal emulators, word processors,
and more.
JavaScript--because of its relative youth--has not had time to
build up any assemblage of standard code with which to build Web-based
applications. One major problem that had stalled this development
was that you were forced to embed your code in the HTML document
in which you wanted to use the script. With the addition of the
SRC attribute to the <script> tag, you can now
write your code in a separate file and merely reference the script
in the page. It is similar to the CODE attribute in the
<applet> tag (this page would load all of the JS
files, display the correct title at the top of the window, and
display a clock above the Welcome to my home page text):
<html>
<head>
<script language="JavaScript" src="header.js"></script>
</head>
<body>
<script language="JavaScript"
src="http://www.foo.com/scripts/timer.js"></script>
<script language="JavaScript" src="body.js"></script>
</body>
</html>
The ability to refer to a javascript file via the SRC attribute
allows you to reuse scripts much more readily than before. It
is expected to be only a matter of time before standard libraries
of code are developed and easily accessible. It is somewhat ironic
that you can find more standard code for Java now than you can
for JavaScript, given that Java is more complicated.
JavaScript and Java Integration top
of page
There are many other examples of differences between Java and
JavaScript, such as memory requirements (and limitations), threads
(Java has them, JavaScript doesn't), and more. But I think that
the differences presented in this chapter will help you to perhaps
change your perception of JavaScript.
You should begin to think of JavaScript not as simply an aspect
of Java, but instead a complementary language that allows you
to greatly control the behavior of your browser. You can now pass
more of the computation and interactivity from your server down
to the user's client browser--thus relieving some of the load
and improving the performance of your server. JavaScript is not
an all-purpose or a universal scripting language, but in the confines
of HTML, plug-ins, browser events, and windows, JavaScript shines
as an easy way to add interactivity to your Web pages.
The decision to use Java or JavaScript will depend not only on
your skills as a programmer, but also on the scope of the Web-related
task at hand. Look carefully at the task and see if the scrolling
text, spinning icon, or calculator might more easily be implemented
in JavaScript. If you need to control most of the browser window
with specialized text or perhaps have a highly sophisticated application,
then Java is surely the way to go.